BOJ_2504_괄호의 값
Stack을 사용해서 괄호의 값을 계산하는 문제
동등한 depth면 더하고 깊은 depth면 2 또는 3을 알맞게 곱한다
숫자가 나오면 pop을 해주고, 앞에서 괄호가 맞으면 pop한 숫자들을 모두 더해 2 또는 3을 곱해주면 된다
중간에 짝이 안 맞으면 flag = True로 줘서 반복문을 빠져나오게 했다
마지막에 괄호가 stack에 남아있을 수 있기 때문에 검사한 후 최종 결과를 낸다
# 스택으로 푸는 문제
# 왼쪽 괄호를 스택에 저장 후에
# 짝이 맞으면 pop을 하고 2를 넣는다?
# -> 숫자가 나오면 계속 pop -> 앞에 괄호랑 맞으면 숫자들 다 더하고 맞는 숫자 곱해서 저장
# -> 마지막에 숫자 다 더해서 계산
str = input()
stack = list()
nums = list()
flag = False
def push_n(n):
if sum(nums) > 0:
n *= sum(nums)
nums.clear()
stack.append(n)
for c in str:
if c == '(' or c == '[':
stack.append(c)
else:
while True:
if not stack:
flag = True
break
p = stack.pop()
if isinstance(p, int):
p_num = int(p)
nums.append(p_num)
elif p == '(' and c == ')':
push_n(2)
break
elif p == '[' and c == ']':
push_n(3)
break
else:
flag = True
break
if flag:
print(0)
break
if not flag:
v_sum = 0
for i in stack:
if not isinstance(i, int):
v_sum = 0
break
v_sum += i
print(v_sum)